﻿using System;
using System.Windows.Data;

namespace Payton.WP7.Converter
{
    public class Int2EnumConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var rv = null as object;

            try
            {
                var i = (int)value;

                rv = i;
            }
            catch
            {
                rv = 0;
            }

            return rv;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var rv = null as object;

            try
            {
                var i = (int)value;

                rv = Enum.Parse(targetType, i.ToString(), true);
            }
            catch
            {
                if (targetType == typeof(int))
                {
                    rv = 0;
                }
                else if (targetType.IsEnum)
                {
                    rv = Enum.Parse(targetType, "0", true);
                }
            }

            return rv;
        }

        #endregion
    }
}
